<template>
  <MainLayout>
    <div class="teacher-students">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span>学生管理</span>
            <div class="header-actions">
              <el-button type="info" @click="showClassManagementDialog = true">
                <el-icon><School /></el-icon>
                班级管理
              </el-button>
              <el-button type="success" @click="showBatchImportDialog = true">
                <el-icon><Upload /></el-icon>
                批量导入
              </el-button>
              <el-button type="primary" @click="showAddStudentDialog = true">
                <el-icon><Plus /></el-icon>
                添加学生
              </el-button>
            </div>
          </div>
        </template>

        <!-- 搜索栏 -->
        <div class="search-bar">
          <el-input
            v-model="searchQuery"
            placeholder="搜索学生姓名或学号"
            style="width: 300px"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-select
            v-model="classFilter"
            placeholder="班级筛选"
            clearable
            style="width: 150px"
          >
            <el-option label="全部班级" value="" />
            <el-option
              v-for="classItem in classes"
              :key="classItem.id"
              :label="classItem.name"
              :value="classItem.id"
            />
          </el-select>

          <el-select
            v-model="statusFilter"
            placeholder="状态筛选"
            clearable
            style="width: 150px"
          >
            <el-option label="全部状态" value="" />
            <el-option label="在读" value="active" />
            <el-option label="休学" value="suspended" />
            <el-option label="毕业" value="graduated" />
          </el-select>

          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </div>

        <!-- 班级统计信息 -->
        <div class="class-stats">
          <el-row :gutter="20">
            <el-col :span="6" v-for="classItem in classStats" :key="classItem.id">
              <el-card shadow="hover" class="stat-card">
                <div class="stat-content">
                  <div class="stat-header">
                    <h4>{{ classItem.name }}</h4>
                    <el-tag :type="classItem.status === 'active' ? 'success' : 'info'">
                      {{ classItem.status === 'active' ? '在读' : '已毕业' }}
                    </el-tag>
                  </div>
                  <div class="stat-numbers">
                    <div class="stat-item">
                      <span class="stat-label">学生数</span>
                      <span class="stat-value">{{ classItem.studentCount }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="stat-label">平均分</span>
                      <span class="stat-value">{{ classItem.averageScore }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="stat-label">解题数</span>
                      <span class="stat-value">{{ classItem.totalProblemsSolved }}</span>
                    </div>
                  </div>
                  <div class="stat-actions">
                    <el-button size="small" @click="viewClassDetail(classItem)">
                      查看详情
                    </el-button>
                    <el-button size="small" type="primary" @click="editClass(classItem)">
                      编辑
                    </el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 学生表格 -->
        <el-table
          :data="filteredStudents"
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="id" label="学号" width="120" />
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="className" label="班级" width="120" />
          <el-table-column prop="email" label="邮箱" width="200" />
          <el-table-column prop="phone" label="电话" width="130" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="problemsSolved" label="解题数" width="100" />
          <el-table-column prop="totalScore" label="总分" width="100" />
          <el-table-column prop="lastLogin" label="最后登录" width="180" />
          <el-table-column label="操作" width="250">
            <template #default="{ row }">
              <el-button size="small" @click="viewStudent(row)">查看</el-button>
              <el-button size="small" @click="editStudent(row)">编辑</el-button>
              <el-button size="small" type="info" @click="viewProgress(row)">进度</el-button>
              <el-button
                size="small"
                :type="row.status === 'active' ? 'warning' : 'success'"
                @click="toggleStudentStatus(row)"
              >
                {{ row.status === "active" ? "休学" : "复学" }}
              </el-button>
              <el-button size="small" type="danger" @click="deleteStudent(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalStudents"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 添加/编辑学生对话框 -->
      <el-dialog
        v-model="showAddStudentDialog"
        :title="editingStudent ? '编辑学生' : '添加学生'"
        width="600px"
      >
        <el-form
          :model="studentForm"
          :rules="studentRules"
          ref="studentFormRef"
          label-width="100px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学号" prop="id">
                <el-input v-model="studentForm.id" :disabled="!!editingStudent" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="studentForm.name" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="班级" prop="classId">
                <el-select
                  v-model="studentForm.classId"
                  placeholder="选择班级"
                  style="width: 100%"
                >
                  <el-option
                    v-for="classItem in classes"
                    :key="classItem.id"
                    :label="classItem.name"
                    :value="classItem.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select
                  v-model="studentForm.status"
                  placeholder="选择状态"
                  style="width: 100%"
                >
                  <el-option label="在读" value="active" />
                  <el-option label="休学" value="suspended" />
                  <el-option label="毕业" value="graduated" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="studentForm.email" />
          </el-form-item>

          <el-form-item label="电话" prop="phone">
            <el-input v-model="studentForm.phone" />
          </el-form-item>

          <el-form-item label="备注" prop="notes">
            <el-input
              v-model="studentForm.notes"
              type="textarea"
              :rows="3"
              placeholder="学生备注信息..."
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showAddStudentDialog = false">取消</el-button>
            <el-button type="primary" @click="saveStudent">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 查看学生详情对话框 -->
      <el-dialog v-model="showStudentDialog" title="学生详情" width="800px">
        <div v-if="selectedStudent" class="student-detail">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="学号">{{ selectedStudent.id }}</el-descriptions-item>
            <el-descriptions-item label="姓名">{{ selectedStudent.name }}</el-descriptions-item>
            <el-descriptions-item label="班级">{{ selectedStudent.className }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusTagType(selectedStudent.status)">
                {{ getStatusLabel(selectedStudent.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ selectedStudent.email }}</el-descriptions-item>
            <el-descriptions-item label="电话">{{ selectedStudent.phone }}</el-descriptions-item>
            <el-descriptions-item label="解题数">{{ selectedStudent.problemsSolved }}</el-descriptions-item>
            <el-descriptions-item label="总分">{{ selectedStudent.totalScore }}</el-descriptions-item>
            <el-descriptions-item label="最后登录">{{ selectedStudent.lastLogin }}</el-descriptions-item>
            <el-descriptions-item label="注册时间">{{ selectedStudent.createdAt }}</el-descriptions-item>
          </el-descriptions>

          <div class="progress-section" style="margin-top: 20px">
            <h4>学习进度</h4>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="progress-card">
                  <div class="progress-title">已解决题目</div>
                  <div class="progress-number">{{ selectedStudent.problemsSolved }}</div>
                  <div class="progress-bar">
                    <el-progress
                      :percentage="Math.min(selectedStudent.problemsSolved * 10, 100)"
                      :color="customColors"
                    />
                  </div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="progress-card">
                  <div class="progress-title">正确率</div>
                  <div class="progress-number">{{ selectedStudent.acceptanceRate || 0 }}%</div>
                  <div class="progress-bar">
                    <el-progress
                      :percentage="selectedStudent.acceptanceRate || 0"
                      :color="customColors"
                    />
                  </div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="progress-card">
                  <div class="progress-title">排名</div>
                  <div class="progress-number">{{ selectedStudent.rank || "N/A" }}</div>
                  <div class="progress-bar">
                    <el-progress
                      :percentage="selectedStudent.rank ? Math.max(100 - selectedStudent.rank * 2, 0) : 0"
                      :color="customColors"
                    />
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-dialog>

      <!-- 班级管理对话框 -->
      <el-dialog
        v-model="showClassManagementDialog"
        title="班级管理"
        width="1000px"
        :close-on-click-modal="false"
      >
        <div class="class-management">
          <div class="class-header">
            <el-button type="primary" @click="showAddClassDialog = true">
              <el-icon><Plus /></el-icon>
              新建班级
            </el-button>
            <el-button type="success" @click="showBatchStudentDialog = true">
              <el-icon><Upload /></el-icon>
              批量导入学生
            </el-button>
          </div>

          <el-table :data="classes" style="width: 100%" v-loading="classLoading">
            <el-table-column prop="id" label="班级ID" width="100" />
            <el-table-column prop="name" label="班级名称" width="200" />
            <el-table-column prop="studentCount" label="学生数量" width="100">
              <template #default="{ row }">
                <el-tag type="info">{{ getClassStudentCount(row.id) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="averageScore" label="平均分" width="100">
              <template #default="{ row }">
                {{ getClassAverageScore(row.id) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'info'">
                  {{ row.status === 'active' ? '在读' : '已毕业' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="180" />
            <el-table-column label="操作" width="250">
              <template #default="{ row }">
                <el-button size="small" @click="viewClassDetail(row)">查看</el-button>
                <el-button size="small" type="primary" @click="editClass(row)">编辑</el-button>
                <el-button size="small" type="warning" @click="toggleClassStatus(row)">
                  {{ row.status === 'active' ? '毕业' : '激活' }}
                </el-button>
                <el-button size="small" type="danger" @click="deleteClass(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-dialog>

      <!-- 添加/编辑班级对话框 -->
      <el-dialog
        v-model="showAddClassDialog"
        :title="editingClass ? '编辑班级' : '新建班级'"
        width="500px"
      >
        <el-form
          :model="classForm"
          :rules="classRules"
          ref="classFormRef"
          label-width="100px"
        >
          <el-form-item label="班级名称" prop="name">
            <el-input v-model="classForm.name" placeholder="请输入班级名称" />
          </el-form-item>
          <el-form-item label="班级描述" prop="description">
            <el-input
              v-model="classForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入班级描述..."
            />
          </el-form-item>
          <el-form-item label="班级状态" prop="status">
            <el-select v-model="classForm.status" placeholder="选择状态" style="width: 100%">
              <el-option label="在读" value="active" />
              <el-option label="已毕业" value="graduated" />
            </el-select>
          </el-form-item>
          <el-form-item label="最大人数" prop="maxStudents">
            <el-input-number
              v-model="classForm.maxStudents"
              :min="1"
              :max="100"
              placeholder="最大学生数"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showAddClassDialog = false">取消</el-button>
            <el-button type="primary" @click="saveClass">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 班级详情对话框 -->
      <el-dialog
        v-model="showClassDetailDialog"
        :title="`${selectedClass?.name} - 班级详情`"
        width="900px"
      >
        <div v-if="selectedClass" class="class-detail">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="班级名称">{{ selectedClass.name }}</el-descriptions-item>
            <el-descriptions-item label="班级状态">
              <el-tag :type="selectedClass.status === 'active' ? 'success' : 'info'">
                {{ selectedClass.status === 'active' ? '在读' : '已毕业' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="学生数量">{{ getClassStudentCount(selectedClass.id) }}</el-descriptions-item>
            <el-descriptions-item label="平均分">{{ getClassAverageScore(selectedClass.id) }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ selectedClass.createdAt }}</el-descriptions-item>
            <el-descriptions-item label="最大人数">{{ selectedClass.maxStudents || '无限制' }}</el-descriptions-item>
          </el-descriptions>

          <div class="class-students" style="margin-top: 20px">
            <h4>班级学生列表</h4>
            <el-table :data="getClassStudents(selectedClass.id)" style="width: 100%">
              <el-table-column prop="id" label="学号" width="120" />
              <el-table-column prop="name" label="姓名" width="100" />
              <el-table-column prop="problemsSolved" label="解题数" width="100" />
              <el-table-column prop="totalScore" label="总分" width="100" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getStatusTagType(row.status)">
                    {{ getStatusLabel(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template #default="{ row }">
                  <el-button size="small" @click="viewStudent(row)">查看</el-button>
                  <el-button size="small" type="primary" @click="editStudent(row)">编辑</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-dialog>

      <!-- 批量导入学生对话框 -->
      <el-dialog
        v-model="showBatchStudentDialog"
        title="批量导入学生"
        width="600px"
      >
        <div class="batch-import">
          <el-alert
            title="批量导入说明"
            type="info"
            :closable="false"
            show-icon
            style="margin-bottom: 20px"
          >
            <ul>
              <li>支持 Excel 文件导入 (.xlsx, .xls)</li>
              <li>文件格式：学号、姓名、邮箱、电话、班级ID</li>
              <li>第一行为表头，从第二行开始为数据</li>
              <li>班级ID 必须与现有班级ID 匹配</li>
            </ul>
          </el-alert>

          <el-form :model="batchForm" label-width="100px">
            <el-form-item label="选择班级">
              <el-select v-model="batchForm.classId" placeholder="选择要导入的班级" style="width: 100%">
                <el-option
                  v-for="classItem in classes"
                  :key="classItem.id"
                  :label="classItem.name"
                  :value="classItem.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="上传文件">
              <el-upload
                ref="uploadRef"
                :file-list="fileList"
                :auto-upload="false"
                :on-change="handleFileChange"
                accept=".xlsx,.xls"
                drag
              >
                <el-icon class="el-icon--upload"><Upload /></el-icon>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 .xlsx, .xls 格式文件
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showBatchStudentDialog = false">取消</el-button>
            <el-button type="primary" @click="handleBatchImport" :loading="batchImporting">
              开始导入
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 批量导入学生对话框 -->
      <el-dialog
        v-model="showBatchImportDialog"
        title="批量导入学生"
        width="700px"
        :close-on-click-modal="false"
      >
        <div class="batch-import">
          <!-- 导入说明 -->
          <el-alert
            title="导入说明"
            type="info"
            :closable="false"
            show-icon
            class="import-info"
          >
            <template #default>
              <div>
                <p>1. 请下载Excel模板，按照模板格式填写学生信息</p>
                <p>2. 支持的文件格式：.xlsx, .xls, .csv</p>
                <p>3. 必填字段：学号、姓名、邮箱、班级</p>
                <p>4. 学号必须唯一，不能重复</p>
                <p>5. 邮箱格式必须正确</p>
              </div>
            </template>
          </el-alert>

          <!-- 选择班级 -->
          <el-form :model="batchForm" label-width="100px" class="batch-form">
            <el-form-item label="目标班级" required>
              <el-select
                v-model="batchForm.classId"
                placeholder="请选择要导入的班级"
                style="width: 100%"
              >
                <el-option
                  v-for="classItem in classes"
                  :key="classItem.id"
                  :label="classItem.name"
                  :value="classItem.id"
                />
              </el-select>
            </el-form-item>
          </el-form>

          <!-- 文件上传 -->
          <div class="upload-section">
            <el-upload
              ref="uploadRef"
              :action="uploadAction"
              :headers="uploadHeaders"
              :data="uploadData"
              :before-upload="beforeUpload"
              :on-success="onUploadSuccess"
              :on-error="onUploadError"
              :on-exceed="onExceed"
              :file-list="fileList"
              :limit="1"
              accept=".xlsx,.xls,.csv"
              drag
              class="batch-upload"
            >
              <el-icon class="el-icon--upload"><Upload /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传 xlsx/xls/csv 文件，且不超过 10MB
                </div>
              </template>
            </el-upload>
          </div>

          <!-- 下载模板 -->
          <div class="template-download">
            <el-button type="info" @click="downloadTemplate" :icon="Download">
              <el-icon><Download /></el-icon>
              下载Excel模板
            </el-button>
            <el-button type="primary" @click="downloadSampleData" :icon="Document">
              <el-icon><Document /></el-icon>
              下载示例数据
            </el-button>
          </div>

          <!-- 导入进度 -->
          <div v-if="batchImporting" class="import-progress">
            <el-progress
              :percentage="importProgress"
              :status="importProgress === 100 ? 'success' : ''"
              :stroke-width="8"
            />
            <p class="progress-text">{{ importProgressText }}</p>
          </div>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showBatchImportDialog = false">取消</el-button>
            <el-button
              type="primary"
              @click="startBatchImport"
              :loading="batchImporting"
              :disabled="!batchForm.classId || fileList.length === 0"
            >
              {{ batchImporting ? '导入中...' : '开始导入' }}
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Search, School, Upload, Download, Document } from "@element-plus/icons-vue";
import MainLayout from '@/layouts/MainLayout.vue';

interface Student {
  id: string;
  name: string;
  className: string;
  classId: string;
  email: string;
  phone: string;
  status: "active" | "suspended" | "graduated";
  problemsSolved: number;
  totalScore: number;
  acceptanceRate?: number;
  rank?: number;
  lastLogin: string;
  createdAt: string;
  notes?: string;
}

interface Class {
  id: string;
  name: string;
  description?: string;
  status: "active" | "graduated";
  maxStudents?: number;
  createdAt: string;
}

const loading = ref(false);
const classLoading = ref(false);
const searchQuery = ref("");
const classFilter = ref("");
const statusFilter = ref("");
const currentPage = ref(1);
const pageSize = ref(20);
const totalStudents = ref(0);
const showAddStudentDialog = ref(false);
const showStudentDialog = ref(false);
const showClassManagementDialog = ref(false);
const showAddClassDialog = ref(false);
const showClassDetailDialog = ref(false);
const showBatchImportDialog = ref(false);
const editingStudent = ref<Student | null>(null);
const editingClass = ref<Class | null>(null);
const selectedStudent = ref<Student | null>(null);
const selectedClass = ref<Class | null>(null);
const studentFormRef = ref();
const classFormRef = ref();
const uploadRef = ref();
const fileList = ref([]);
const batchImporting = ref(false);
const importProgress = ref(0);
const importProgressText = ref('准备导入...');
const uploadAction = ref('/api/students/batch-import');
const uploadHeaders = ref({});
const uploadData = ref({});

const studentForm = ref<{
  id: string;
  name: string;
  classId: string;
  status: "active" | "suspended" | "graduated";
  email: string;
  phone: string;
  notes: string;
}>({
  id: "",
  name: "",
  classId: "",
  status: "active",
  email: "",
  phone: "",
  notes: "",
});

const classForm = ref<{
  id: string;
  name: string;
  description: string;
  status: "active" | "graduated";
  maxStudents: number;
}>({
  id: "",
  name: "",
  description: "",
  status: "active",
  maxStudents: 50,
});

const batchForm = ref<{
  classId: string;
}>({
  classId: "",
});

const studentRules = {
  id: [
    { required: true, message: "请输入学号", trigger: "blur" },
    { min: 5, max: 20, message: "长度在 5 到 20 个字符", trigger: "blur" },
  ],
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
  classId: [{ required: true, message: "请选择班级", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  email: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入电话号码", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
};

const classRules = {
  name: [
    { required: true, message: "请输入班级名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择班级状态", trigger: "change" }],
  maxStudents: [
    { required: true, message: "请输入最大学生数", trigger: "blur" },
    { type: "number", min: 1, max: 100, message: "学生数在 1 到 100 之间", trigger: "blur" },
  ],
};

// 模拟班级数据
const classes = ref<Class[]>([
  { id: "1", name: "计算机科学1班", status: "active", createdAt: "2023-01-01" },
  { id: "2", name: "计算机科学2班", status: "active", createdAt: "2023-02-01" },
  { id: "3", name: "软件工程1班", status: "active", createdAt: "2023-03-01" },
  { id: "4", name: "软件工程2班", status: "active", createdAt: "2023-04-01" },
]);

// 模拟学生数据
const students = ref<Student[]>([
  {
    id: "2021001",
    name: "张三",
    className: "计算机科学1班",
    classId: "1",
    email: "zhangsan@example.com",
    phone: "13800138001",
    status: "active",
    problemsSolved: 25,
    totalScore: 1850,
    acceptanceRate: 85,
    rank: 5,
    lastLogin: "2024-01-15 16:30:00",
    createdAt: "2021-09-01 08:00:00",
    notes: "学习积极，算法基础扎实",
  },
  {
    id: "2021002",
    name: "李四",
    className: "计算机科学1班",
    classId: "1",
    email: "lisi@example.com",
    phone: "13800138002",
    status: "active",
    problemsSolved: 18,
    totalScore: 1420,
    acceptanceRate: 78,
    rank: 12,
    lastLogin: "2024-01-15 14:20:00",
    createdAt: "2021-09-01 08:00:00",
    notes: "需要加强数据结构练习",
  },
]);

const filteredStudents = computed(() => {
  let filtered = students.value;

  if (searchQuery.value) {
    filtered = filtered.filter(
      (student) =>
        student.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        student.id.toLowerCase().includes(searchQuery.value.toLowerCase()),
    );
  }

  if (classFilter.value) {
    filtered = filtered.filter(
      (student) => student.classId === classFilter.value,
    );
  }

  if (statusFilter.value) {
    filtered = filtered.filter(
      (student) => student.status === statusFilter.value,
    );
  }

  return filtered;
});

const classStats = computed(() => {
  return classes.value.map(classItem => ({
    ...classItem,
    studentCount: getClassStudentCount(classItem.id),
    averageScore: getClassAverageScore(classItem.id),
    totalProblemsSolved: getClassTotalProblemsSolved(classItem.id)
  }));
});

const customColors = [
  { color: "#f56c6c", percentage: 20 },
  { color: "#e6a23c", percentage: 40 },
  { color: "#5cb87a", percentage: 60 },
  { color: "#1989fa", percentage: 80 },
  { color: "#6f7ad3", percentage: 100 },
];

const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    active: "success",
    suspended: "warning",
    graduated: "info",
  };
  return typeMap[status] || "info";
};

const getStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    active: "在读",
    suspended: "休学",
    graduated: "毕业",
  };
  return labelMap[status] || status;
};

// 班级相关工具函数
const getClassStudentCount = (classId: string) => {
  return students.value.filter(student => student.classId === classId).length;
};

const getClassAverageScore = (classId: string) => {
  const classStudents = students.value.filter(student => student.classId === classId);
  if (classStudents.length === 0) return 0;
  const totalScore = classStudents.reduce((sum, student) => sum + student.totalScore, 0);
  return Math.round(totalScore / classStudents.length);
};

const getClassTotalProblemsSolved = (classId: string) => {
  const classStudents = students.value.filter(student => student.classId === classId);
  return classStudents.reduce((sum, student) => sum + student.problemsSolved, 0);
};

const getClassStudents = (classId: string) => {
  return students.value.filter(student => student.classId === classId);
};

const handleSearch = () => {
  currentPage.value = 1;
};

const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
};

const viewStudent = (student: Student) => {
  selectedStudent.value = student;
  showStudentDialog.value = true;
};

const editStudent = (student: Student) => {
  editingStudent.value = student;
  studentForm.value = {
    id: student.id,
    name: student.name,
    classId: student.classId,
    status: student.status,
    email: student.email,
    phone: student.phone,
    notes: student.notes || "",
  };
  showAddStudentDialog.value = true;
};

const viewProgress = (student: Student) => {
  selectedStudent.value = student;
  showStudentDialog.value = true;
};

const toggleStudentStatus = async (student: Student) => {
  try {
    const action = student.status === "active" ? "休学" : "复学";
    await ElMessageBox.confirm(
      `确定要${action}学生 ${student.name} 吗？`,
      `确认${action}`,
      { type: "warning" },
    );

    student.status = student.status === "active" ? "suspended" : "active";
    ElMessage.success(`学生${action}成功`);
  } catch {
    // 用户取消操作
  }
};

const deleteStudent = async (student: Student) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除学生 ${student.name} 吗？此操作不可恢复！`,
      "确认删除",
      { type: "error" },
    );

    const index = students.value.findIndex((s) => s.id === student.id);
    if (index !== -1) {
      students.value.splice(index, 1);
      ElMessage.success("学生删除成功");
    }
  } catch {
    // 用户取消操作
  }
};

// 班级管理相关函数
const viewClassDetail = (classItem: Class) => {
  selectedClass.value = classItem;
  showClassDetailDialog.value = true;
};

const editClass = (classItem: Class) => {
  editingClass.value = classItem;
  classForm.value = {
    id: classItem.id,
    name: classItem.name,
    description: classItem.description || "",
    status: classItem.status,
    maxStudents: classItem.maxStudents || 50,
  };
  showAddClassDialog.value = true;
};

const toggleClassStatus = async (classItem: Class) => {
  try {
    const action = classItem.status === 'active' ? '毕业' : '激活';
    await ElMessageBox.confirm(
      `确定要将班级 ${classItem.name} 标记为${action}吗？`,
      `确认${action}`,
      { type: "warning" },
    );

    classItem.status = classItem.status === 'active' ? 'graduated' : 'active';
    ElMessage.success(`班级${action}成功`);
  } catch {
    // 用户取消操作
  }
};

const deleteClass = async (classItem: Class) => {
  try {
    const studentCount = getClassStudentCount(classItem.id);
    if (studentCount > 0) {
      ElMessage.warning(`该班级还有 ${studentCount} 名学生，无法删除！`);
      return;
    }

    await ElMessageBox.confirm(
      `确定要删除班级 ${classItem.name} 吗？此操作不可恢复！`,
      "确认删除",
      { type: "error" },
    );

    const index = classes.value.findIndex((c) => c.id === classItem.id);
    if (index !== -1) {
      classes.value.splice(index, 1);
      ElMessage.success("班级删除成功");
    }
  } catch {
    // 用户取消操作
  }
};

const saveClass = async () => {
  if (!classFormRef.value) return;

  try {
    await classFormRef.value.validate();

    if (editingClass.value) {
      // 编辑班级
      const index = classes.value.findIndex(
        (c) => c.id === editingClass.value!.id,
      );
      if (index !== -1) {
        classes.value[index] = {
          ...classes.value[index],
          name: classForm.value.name,
          description: classForm.value.description,
          status: classForm.value.status,
          maxStudents: classForm.value.maxStudents,
        };
      }
      ElMessage.success("班级信息更新成功");
    } else {
      // 新建班级
      const newClass: Class = {
        id: Date.now().toString(),
        name: classForm.value.name,
        description: classForm.value.description,
        status: classForm.value.status,
        maxStudents: classForm.value.maxStudents,
        createdAt: new Date().toLocaleString(),
      };
      classes.value.push(newClass);
      ElMessage.success("班级创建成功");
    }

    showAddClassDialog.value = false;
    resetClassForm();
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

const resetClassForm = () => {
  classForm.value = {
    id: "",
    name: "",
    description: "",
    status: "active",
    maxStudents: 50,
  };
  editingClass.value = null;
};

// 批量导入相关方法
const beforeUpload = (file: any) => {
  const isValidType = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 
                       'application/vnd.ms-excel', 
                       'text/csv'].includes(file.type);
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isValidType) {
    ElMessage.error('只能上传 Excel 或 CSV 文件!');
    return false;
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!');
    return false;
  }

  // 设置上传数据
  uploadData.value = {
    classId: batchForm.value.classId
  };

  return true;
};

const onUploadSuccess = (response: any, file: any) => {
  ElMessage.success('文件上传成功，开始处理数据...');
  startBatchImport();
};

const onUploadError = (error: any) => {
  ElMessage.error('文件上传失败: ' + error.message);
  batchImporting.value = false;
  importProgress.value = 0;
  importProgressText.value = '准备导入...';
};

const onExceed = () => {
  ElMessage.warning('只能上传一个文件');
};

const startBatchImport = async () => {
  if (!batchForm.value.classId) {
    ElMessage.error('请选择目标班级');
    return;
  }

  if (fileList.value.length === 0) {
    ElMessage.error('请先上传文件');
    return;
  }

  try {
    batchImporting.value = true;
    importProgress.value = 0;
    importProgressText.value = '开始导入...';

    // 模拟导入进度
    const progressInterval = setInterval(() => {
      if (importProgress.value < 90) {
        importProgress.value += Math.random() * 20;
        importProgressText.value = `正在导入学生数据... ${Math.round(importProgress.value)}%`;
      }
    }, 500);

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 3000));

    clearInterval(progressInterval);
    importProgress.value = 100;
    importProgressText.value = '导入完成！';

    // 模拟导入成功
    setTimeout(() => {
      ElMessage.success('批量导入成功！');
      showBatchImportDialog.value = false;
      batchImporting.value = false;
      importProgress.value = 0;
      importProgressText.value = '准备导入...';
      fileList.value = [];
      batchForm.value.classId = '';
      
      // 刷新学生列表
      loadStudents();
    }, 1000);

  } catch (error) {
    ElMessage.error('导入失败: ' + error.message);
    batchImporting.value = false;
    importProgress.value = 0;
    importProgressText.value = '准备导入...';
  }
};

const downloadTemplate = () => {
  // 创建Excel模板数据
  const templateData = [
    ['学号', '姓名', '邮箱', '电话', '状态', '备注'],
    ['2021001', '张三', 'zhangsan@example.com', '13800138001', 'active', '示例学生1'],
    ['2021002', '李四', 'lisi@example.com', '13800138002', 'active', '示例学生2'],
    ['2021003', '王五', 'wangwu@example.com', '13800138003', 'active', '示例学生3']
  ];

  // 创建CSV内容
  const csvContent = templateData.map(row => row.join(',')).join('\n');
  
  // 创建下载链接
  const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', '学生导入模板.csv');
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const downloadSampleData = () => {
  // 创建示例数据
  const sampleData = [
    ['学号', '姓名', '邮箱', '电话', '状态', '备注'],
    ['2021001', '张三', 'zhangsan@example.com', '13800138001', 'active', '计算机科学专业'],
    ['2021002', '李四', 'lisi@example.com', '13800138002', 'active', '软件工程专业'],
    ['2021003', '王五', 'wangwu@example.com', '13800138003', 'active', '数据科学专业'],
    ['2021004', '赵六', 'zhaoliu@example.com', '13800138004', 'active', '人工智能专业'],
    ['2021005', '钱七', 'qianqi@example.com', '13800138005', 'active', '网络工程专业']
  ];

  // 创建CSV内容
  const csvContent = sampleData.map(row => row.join(',')).join('\n');
  
  // 创建下载链接
  const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', '学生导入示例数据.csv');
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const saveStudent = async () => {
  if (!studentFormRef.value) return;

  try {
    await studentFormRef.value.validate();

    if (editingStudent.value) {
      // 编辑学生
      const index = students.value.findIndex(
        (s) => s.id === editingStudent.value!.id,
      );
      if (index !== -1) {
        const className =
          classes.value.find((c) => c.id === studentForm.value.classId)?.name ||
          "";
        students.value[index] = {
          ...students.value[index],
          name: studentForm.value.name,
          className,
          classId: studentForm.value.classId,
          status: studentForm.value.status,
          email: studentForm.value.email,
          phone: studentForm.value.phone,
          notes: studentForm.value.notes,
        };
      }
      ElMessage.success("学生信息更新成功");
    } else {
      // 添加学生
      const className =
        classes.value.find((c) => c.id === studentForm.value.classId)?.name ||
        "";
      const newStudent: Student = {
        id: studentForm.value.id,
        name: studentForm.value.name,
        className,
        classId: studentForm.value.classId,
        email: studentForm.value.email,
        phone: studentForm.value.phone,
        status: studentForm.value.status as
          | "active"
          | "suspended"
          | "graduated",
        problemsSolved: 0,
        totalScore: 0,
        lastLogin: "从未登录",
        createdAt: new Date().toLocaleString(),
        notes: studentForm.value.notes,
      };
      students.value.push(newStudent);
      ElMessage.success("学生添加成功");
    }

    showAddStudentDialog.value = false;
    resetForm();
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

const resetForm = () => {
  studentForm.value = {
    id: "",
    name: "",
    classId: "",
    status: "active",
    email: "",
    phone: "",
    notes: "",
  };
  editingStudent.value = null;
};

// 加载学生数据
const loadStudents = () => {
  // 这里应该调用实际的API
  // 暂时使用模拟数据
  totalStudents.value = students.value.length;
};

onMounted(() => {
  loadStudents();
});
</script>

<style scoped lang="scss">
.teacher-students {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }

  .search-bar {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
    align-items: center;
  }

  .class-stats {
    margin-bottom: 20px;

    .stat-card {
      .stat-content {
        .stat-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;

          h4 {
            margin: 0;
            color: #303133;
            font-size: 16px;
          }
        }

        .stat-numbers {
          margin-bottom: 16px;

          .stat-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;

            .stat-label {
              color: #606266;
              font-size: 14px;
            }

            .stat-value {
              color: #303133;
              font-weight: bold;
              font-size: 16px;
            }
          }
        }

        .stat-actions {
          display: flex;
          gap: 8px;
        }
      }
    }
  }

  .class-management {
    .class-header {
      display: flex;
      gap: 16px;
      margin-bottom: 20px;
    }
  }

  .class-detail {
    .class-students {
      h4 {
        margin: 0 0 16px 0;
        color: #303133;
        font-size: 16px;
      }
    }
  }

  .batch-import {
    .import-info {
      margin-bottom: 20px;
      
      p {
        margin: 5px 0;
        font-size: 14px;
        line-height: 1.5;
      }
    }

    .batch-form {
      margin-bottom: 20px;
    }

    .upload-section {
      margin-bottom: 20px;
    }

    .batch-upload {
      width: 100%;
      
      .el-upload-dragger {
        width: 100%;
        height: 180px;
        border: 2px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: border-color 0.3s;
        
        &:hover {
          border-color: #409eff;
        }
        
        .el-icon--upload {
          font-size: 67px;
          color: #c0c4cc;
          margin: 40px 0 16px;
          line-height: 50px;
        }
        
        .el-upload__text {
          color: #606266;
          font-size: 14px;
          text-align: center;
          
          em {
            color: #409eff;
            font-style: normal;
          }
        }
        
        .el-upload__tip {
          font-size: 12px;
          color: #606266;
          text-align: center;
          margin-top: 10px;
        }
      }
    }

    .template-download {
      display: flex;
      gap: 12px;
      margin-bottom: 20px;
      justify-content: center;
    }

    .import-progress {
      margin-top: 20px;
      text-align: center;
      
      .progress-text {
        margin-top: 10px;
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }

  .student-detail {
    .progress-section {
      h4 {
        margin: 0 0 16px 0;
        color: #303133;
        font-size: 16px;
      }

      .progress-card {
        text-align: center;
        padding: 20px;
        border: 1px solid #e4e7ed;
        border-radius: 8px;

        .progress-title {
          font-size: 14px;
          color: #606266;
          margin-bottom: 8px;
        }

        .progress-number {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
          margin-bottom: 12px;
        }

        .progress-bar {
          padding: 0 10px;
        }
      }
    }
  }
}
</style>
